package com.lakeworks.decision.handler;

import com.lakeworks.event.TicketWashModeEvent;
import com.lakeworks.common.domain.ticket.TktDecision;
import com.lakeworks.common.domain.ticket.TktTicket;
import com.lakeworks.common.enums.ticket.TicketBackStatus;
import com.lakeworks.common.enums.ticket.TicketStatus;
import com.lakeworks.decision.BackTicketStateDecision;
import com.lakeworks.decision.base.BaseDecisionHandler;
import com.lakeworks.decision.base.DecisionHandler;
import com.lakeworks.domain.vo.TicketBackVo;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

@Component
public class BackTicketStateHandler extends BaseDecisionHandler implements DecisionHandler<BackTicketStateDecision> {

    @Override
    public TktDecision apply(BackTicketStateDecision decision) {
        TktTicket ticket = decision.getTktTicket();
        System.out.println("执行反馈工单状态决策");
        TicketBackVo backVo = decision.getTicketBackVo();
        backVo.setTicketId(ticket.getChannelTicketId());
        backVo.setChannelId(getChannelId(ticket.getOrderNo()));
        //将反馈推送给平台
        if(backVo.getTicketBackState().equals(TicketBackStatus.HAVEKNOWN.name())){
            ticket.setStatus(TicketStatus.FINISHED.name());
            closeRelevanceTicket(ticket);
        }else if(backVo.getTicketBackState().equals(TicketBackStatus.INCONSISTENCY.name())){
            ticket.setStatus(TicketStatus.PENDING.name());
        }else {
            ticket.setStatus(TicketStatus.AWAITING.name());
        }
        updateTicketState(ticket);
        //判断是否是洗前沟通 触发修改洗涤方式
        if (backVo.getTicketBackState().equals(TicketBackStatus.BEFOREWASH.name())) {
            if (!CollectionUtils.isEmpty(backVo.getBarcodeVos())) {
                getApplicationContext().publishEvent(new TicketWashModeEvent(this, backVo.getBarcodeVos()));
            }
        }
        /*getLog().info("触发工单变化（工单完结）事件---orderNo:[{}]",ticket.getOrderNo());
        getApplicationContext().publishEvent(new TicketHoldingEvent(this,ticket.getOrderNo()));*/
        try {
            getLog().info("工厂反馈"+TicketBackStatus.valueOf(backVo.getTicketBackState()).getName()+"----param:[{}]",backVo);
            getDetectMethodAnnotation().execute(getMerchantAsync(), backVo.getTicketBackState(), backVo);
        }catch (Exception e){
            getLog().error("channel ---"+ backVo.getTicketBackState()+"---error:[{}]",e);
        }
        return getTktDecision(ticket, decision);
    }





}
